package handler;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONObject;

import pojo.bean.TreeNode;
import pojo.bean.TreeNodeStateEnum;
import tool.JSONObjectConverter;

public class TreeNodeDataRequestHandler extends HttpServlet {
    private static final long serialVersionUID = -6774259321980892831L;
    private Random random;

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json;charset=UTF-8");
        List<TreeNode> nodes = new ArrayList<>();
        List<JSONObject> nodeObjects = null;
        for (int i = 0; i < 10; i++) {
            int id = random.nextInt(Integer.MAX_VALUE);
            int j = i + 1;
            List<TreeNode> children = new ArrayList<>(j);
            for (int k = 0; k < j; k++) {
                int idField = random.nextInt(Integer.MAX_VALUE);
                TreeNode childNode = new TreeNode(idField, "节点" + idField, TreeNodeStateEnum.UNCHECKED.getState(), null);
                children.add(childNode);
            }
            List<JSONObject> childrenObjects = JSONObjectConverter.convert(children);
            TreeNode node = new TreeNode(id, "节点" + id, TreeNodeStateEnum.UNCHECKED.getState(), childrenObjects);
            nodes.add(node);
        }
        nodeObjects = JSONObjectConverter.convert(nodes);
        PrintWriter out = resp.getWriter();
        JSONObject[] array = nodeObjects.toArray(new JSONObject[nodeObjects.size()]);
        out.print(Arrays.toString(array));
    }

    @Override
    public void init() throws ServletException {
        random = new Random();
        super.init();
    }

}
